package com.liao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liao.dto.BorrowDTO;
import com.liao.dto.ReturnDTO;
import com.liao.entity.Book;
import com.liao.entity.BorrowRecord;
import com.liao.entity.User;
import com.liao.mapper.BorrowRecordMapper;
import com.liao.service.BookService;
import com.liao.service.BorrowRecordService;
import com.liao.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 借阅记录服务实现类
 */
@Service
public class BorrowRecordServiceImpl extends ServiceImpl<BorrowRecordMapper, BorrowRecord> implements BorrowRecordService {

    @Resource
    private UserService userService;

    @Resource
    private BookService bookService;

    /**
     * 分页查询借阅记录列表
     *
     * @param page   分页参数
     * @param userId 用户ID（可选）
     * @param bookId 图书ID（可选）
     * @param status 状态（可选）
     * @return 分页借阅记录列表
     */
    @Override
    public Page<BorrowRecord> getBorrowPage(Page<BorrowRecord> page, Long userId, Long bookId, Integer status) {
        LambdaQueryWrapper<BorrowRecord> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        queryWrapper.eq(userId != null, BorrowRecord::getUserId, userId)
                .eq(bookId != null, BorrowRecord::getBookId, bookId)
                .eq(status != null, BorrowRecord::getStatus, status)
                .orderByDesc(BorrowRecord::getCreateTime);
        
        // 查询并返回结果
        return this.page(page, queryWrapper);
    }

    /**
     * 借阅图书
     *
     * @param borrowDTO 借阅信息
     * @return 借阅记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BorrowRecord borrowBook(BorrowDTO borrowDTO) {
        // 检查用户是否存在
        User user = userService.getById(borrowDTO.getUserId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查图书是否存在
        Book book = bookService.getById(borrowDTO.getBookId());
        if (book == null) {
            throw new RuntimeException("图书不存在");
        }
        
        // 检查图书库存
        if (book.getStock() <= 0) {
            throw new RuntimeException("图书库存不足");
        }
        
        // 检查用户是否已借阅该图书
        LambdaQueryWrapper<BorrowRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BorrowRecord::getUserId, borrowDTO.getUserId())
                .eq(BorrowRecord::getBookId, borrowDTO.getBookId())
                .eq(BorrowRecord::getStatus, 0); // 0-借阅中
        if (this.count(queryWrapper) > 0) {
            throw new RuntimeException("您已借阅该图书，请先归还");
        }
        
        // 创建借阅记录
        BorrowRecord borrowRecord = new BorrowRecord();
        borrowRecord.setUserId(borrowDTO.getUserId());
        borrowRecord.setBookId(borrowDTO.getBookId());
        borrowRecord.setBorrowDate(LocalDateTime.now());
        borrowRecord.setExpectedReturnDate(borrowDTO.getExpectedReturnDate());
        borrowRecord.setStatus(0); // 0-借阅中
        borrowRecord.setCreateTime(LocalDateTime.now());
        borrowRecord.setUpdateTime(LocalDateTime.now());
        
        // 保存借阅记录
        this.save(borrowRecord);
        
        // 更新图书库存
        bookService.updateStock(book.getId(), -1);
        
        return borrowRecord;
    }

    /**
     * 归还图书
     *
     * @param returnDTO 归还信息
     * @return 借阅记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BorrowRecord returnBook(ReturnDTO returnDTO) {
        // 检查借阅记录是否存在
        BorrowRecord borrowRecord = this.getById(returnDTO.getBorrowId());
        if (borrowRecord == null) {
            throw new RuntimeException("借阅记录不存在");
        }
        
        // 检查用户ID是否匹配
        if (!borrowRecord.getUserId().equals(returnDTO.getUserId())) {
            throw new RuntimeException("用户ID不匹配");
        }
        
        // 检查图书ID是否匹配
        if (!borrowRecord.getBookId().equals(returnDTO.getBookId())) {
            throw new RuntimeException("图书ID不匹配");
        }
        
        // 检查借阅状态
        if (borrowRecord.getStatus() != 0 && borrowRecord.getStatus() != 2) {
            throw new RuntimeException("该图书已归还");
        }
        
        // 更新借阅记录
        LocalDateTime now = LocalDateTime.now();
        borrowRecord.setActualReturnDate(now);
        
        // 判断是否逾期
        if (now.isAfter(borrowRecord.getExpectedReturnDate())) {
            borrowRecord.setStatus(3); // 3-逾期已还
        } else {
            borrowRecord.setStatus(1); // 1-已归还
        }
        
        borrowRecord.setUpdateTime(now);
        
        // 更新借阅记录
        this.updateById(borrowRecord);
        
        // 更新图书库存
        bookService.updateStock(borrowRecord.getBookId(), 1);
        
        return borrowRecord;
    }

    /**
     * 获取用户的借阅历史
     *
     * @param page   分页参数
     * @param userId 用户ID
     * @return 用户借阅历史
     */
    @Override
    public Page<BorrowRecord> getUserBorrowHistory(Page<BorrowRecord> page, Long userId) {
        LambdaQueryWrapper<BorrowRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BorrowRecord::getUserId, userId)
                .orderByDesc(BorrowRecord::getCreateTime);
        
        return this.page(page, queryWrapper);
    }

    /**
     * 获取图书的借阅历史
     *
     * @param page   分页参数
     * @param bookId 图书ID
     * @return 图书借阅历史
     */
    @Override
    public Page<BorrowRecord> getBookBorrowHistory(Page<BorrowRecord> page, Long bookId) {
        LambdaQueryWrapper<BorrowRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BorrowRecord::getBookId, bookId)
                .orderByDesc(BorrowRecord::getCreateTime);
        
        return this.page(page, queryWrapper);
    }
}